//
//  BPForgetPasswordViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/1.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPForgetPasswordViewController.h"
#import "AccountTool.h"
#import "BPRegisterAccountParam.h"
#import "BPAccount.h"
#import "BPhttpTool.h"
#import "MJExtension.h"
#import "BPLoginViewController.h"
#import "MBProgressHUD+MJ.h"

//获取验证码
#define authcodeGetTitle @"获取验证码"

#define messageBtnColor BPColor(244, 133, 142)

//计时器间隔秒数
#define maxSecond 120

@interface BPForgetPasswordViewController ()<UIScrollViewDelegate>{
    int _currentSecond;//当前的秒数
    
    BPAccount *_account;
}

@end

@implementation BPForgetPasswordViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)setUpNav
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(5.0f, 20.0f, 50.0f, 50.0f);
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(dismissLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}

- (void)dismissLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self drawUIView];
    [self setUpNav];
    
    _currentSecond = maxSecond;
    _paramAccount = [[BPRegisterAccountParam alloc] init];
    _account = [[BPAccount alloc] init];
    [self setUpAccountAndPassword];
   // self.view.backgroundColor = [UIColor whiteColor];
//    CGFloat textY = BPScreenNavY;
    
    
}


- (void)setUpAccountAndPassword{
    CGFloat textY = CGRectGetMaxY(_headView.frame);
    CGFloat textH = 47.0f;
    CGFloat textX = 20.0f;
    CGFloat textW = BPScreenW - 40.0f;
    NSArray *placeArry = [NSArray arrayWithObjects:@"请输入手机号",@"请输入短信验证码",@"请输入6~20位新密码", nil];
    
    
    UILabel *add = [[UILabel alloc] initWithFrame:CGRectMake(textX, textY, 50, textH)];
    add.text = @"账号:";
    add.alpha = 0.5;
    add.font = [UIFont systemFontOfSize:18];
    [_scrollView addSubview:add];
    
    _phoneNmuber = [[UITextField alloc] initWithFrame:CGRectMake(textX + 50, textY, textW, textH)];
    _phoneNmuber.placeholder = placeArry[0];
     _phoneNmuber.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:_phoneNmuber];
    
    _message = [[UITextField alloc] init];
    _message.frame = CGRectMake(textX + 50, textY, textW - 100, textH);
    _message.y = _phoneNmuber.y + textH;
    _message.x = textX + 50;
    _message.placeholder = placeArry[1];
    _message.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:_message];
    
    _messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateNormal];
    _messageBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [_messageBtn setBackgroundColor:messageBtnColor];
    _messageBtn.size = CGSizeMake(80.0f, 21.0f);
    _messageBtn.x = BPScreenW - _messageBtn.width - BPStatusCellInset;
    _messageBtn.y = _message.y + 10;
    [_messageBtn.layer setCornerRadius:11.0f];
    [_scrollView addSubview:_messageBtn];
    [_messageBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *mima = [[UILabel alloc] initWithFrame:CGRectMake(textX, _message.y + textH, 50, textH)];
    mima.text = @"密码:";
    mima.alpha = 0.5;
    mima.font = [UIFont systemFontOfSize:18];
    [_scrollView addSubview:mima];
    
    _passWord = [[UITextField alloc] init];
    _passWord.frame = _message.bounds;
    _passWord.y = _message.y + textH;
    _passWord.x = textX + 50;
    _passWord.placeholder = placeArry[2];
    _passWord.secureTextEntry = YES;
    [_scrollView addSubview:_passWord];
    
    
    UIButton *changePass = [UIButton buttonWithType:UIButtonTypeCustom];
    [changePass setTitle:@"修改并登录" forState:UIControlStateNormal];
    [self addBtn:changePass];
    //    changePass.center = CGPointMake((BPScreenW / 2.0), _passWord.y + _passWord.height + 63.0f);
    changePass.frame = CGRectMake(25, _passWord.y + _passWord.height + 63.0f, self.view.frame.size.width - 50, 30);
    
    [changePass addTarget:self action:@selector(changePassOrNewPhone) forControlEvents:UIControlEventTouchUpInside];
    self.changePass = changePass;
    for (int i = 0; i < 3; i ++) {
        BPLineView *line = [[BPLineView alloc] initWithFrame:CGRectMake(60, textY + textH * (i+1), BPScreenW, 0.7)];
        [_scrollView addSubview:line];
    }
}

- (void)addBtn:(UIButton *)button
{
    button.size = CGSizeMake(106.0f, 32.0f);
    button.backgroundColor = BPGlobaThemeColor;
    [button.layer setCornerRadius:16.0f];
    [_scrollView addSubview:button];
}

- (void)sendMessage
{
    if ([self checkPhoneNumber]==YES) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f
                                                  target:self
                                                selector:@selector(updateAuthcodeBtn:)
                                                userInfo:nil
                                                 repeats:YES];
        [_timer fire];
        [BPhttpTool get:[NSString stringWithFormat:@"%@user/verify/mobile/%@",BPhttp,_phoneNmuber.text] params:nil success:^(id responseObj) {
            if (responseObj != nil) {
                NSDictionary *dic = responseObj;
                _paramAccount.verifycode = dic[@"code"];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        
//        [AccountTool receiveMessageCode:_phoneNmuber.text success:^(BPRegisterAccountParam *result) {
//            _paramAccount.verifycode = result.code;
//            BPLog(@"%@",_paramAccount.verifycode);
//        } failure:^(NSError *error) {
//            BPLog(@"验证码获取失败");
//        }];
    }
}

- (void)updateAuthcodeBtn:(NSTimer *)time
{
    if (_currentSecond <= 0) {
        [self endTimer];
        _currentSecond = maxSecond;
        _messageBtn.enabled = YES;
        [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateNormal];
        [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateDisabled];
        [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateHighlighted];
    }
    else
    {
        _messageBtn.enabled = NO;
        NSString *timeTipInfo = [NSString stringWithFormat:@"%i秒后获取",_currentSecond];
        [_messageBtn setTitle:timeTipInfo forState:UIControlStateNormal];
        [_messageBtn setTitle:timeTipInfo forState:UIControlStateDisabled];
        [_messageBtn setTitle:timeTipInfo forState:UIControlStateHighlighted];
    }
    _currentSecond--;
}

#pragma mark 停止计时器
-(void)endTimer
{
    if (_timer)
    {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)changePassOrNewPhone
{
    if ([self checkPhoneNumber] == YES && [_message.text isEqualToString:_paramAccount.verifycode] == YES && [self isStrEmpty:_passWord.text] == NO) {
        //_paramAccount.username = _phoneNmuber.text;
        _paramAccount.password = _passWord.text;
        _paramAccount.mobile = _phoneNmuber.text;
        _paramAccount.uid = [AccountTool account].uid;
        //NSDictionary *param = [NSDictionary dictionary];
        //param = [_paramAccount keyValues];
        //NSLog(@"%@",param);
        
        
        
        NSLog(@"电话 = %@", self.phoneNmuber.text);
        NSLog(@"密码 = %@", self.passWord.text);
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:self.phoneNmuber.text forKey:@"mobile"];
        [param setValue:self.passWord.text forKey:@"password"];
        
        
        
        [BPhttpTool post:[NSString stringWithFormat:@"%@user/resetpwd",BPhttp] params:param success:^(id responseObj) {
            NSLog(@"重置的密码%@", responseObj);
            NSDictionary *dic = responseObj;
            if ([dic[@"status"] intValue] == 0) {
                //[MBProgressHUD showMessage2:responseObj[@"info"]];
                [self showAlertWithMessage:@"更改失败"];
    
            }else{
                [MBProgressHUD showSuccess:@"更改成功"];
                BPAccount *accountPass= [[BPAccount alloc] init];
                accountPass.password = _passWord.text;
                [AccountTool save:accountPass];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failure:^(NSError *error) {
            [self showAlertWithMessage:@"网络错误"];
        }];
        
    }else{
        if ([_message.text isEqualToString:_paramAccount.verifycode] == NO) {
            [self showAlertWithMessage:@"验证码有误"];
            
        }else if ([self isStrEmpty:_passWord.text] == YES){
            [self showAlertWithMessage:@"密码为空"];
        }
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (BOOL)checkPhoneNumber
{
    NSString *phoneNumber = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumber];
    
    BOOL isMatch = [pred evaluateWithObject:_phoneNmuber.text];
    
    if (!isMatch) {
        [self showAlertWithMessage:@"请输入正确的手机号码"];
        return NO;
    }else
    {
        return YES;
    }
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alert show];
}

//判断text是否为空
-(BOOL)isStrEmpty:(NSString*)str
{
    if (str == nil || str == NULL)
    {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([str length] <= 0)
    {
        return YES;
    }
    return NO;
}






- (void)drawUIView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:_scrollView];
    UITapGestureRecognizer *hideKEY= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [_scrollView addGestureRecognizer:hideKEY];
    _scrollView.delegate = self;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, 150.0f)];
    //_headView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LoginImage"]];
    [_scrollView addSubview:_headView];
    
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(_headView.frame.size.width / 2 - 100, 0, 200, 140)];
    imageV.image = [UIImage imageNamed:@"LoginImage"];
    [_headView addSubview:imageV];
    
    UIImageView *langXian = [[UIImageView alloc] initWithFrame:CGRectMake(0, _headView.frame.size.height - 5, self.headView.frame.size.width, 5)];
    langXian.image = [UIImage imageNamed:@"波纹线"];
    [_headView addSubview:langXian];
}


- (void)hideKeyBoard
{
    [self.view endEditing:YES];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
